package pl.vanta.mjuzik.gui.panels;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import pl.vanta.mjuzik.MusicUtils;
import pl.vanta.mjuzik.gui.listeners.PlaylistListener;
import pl.vanta.mjuzik.gui.tables.PlaylistTableModel;
import pl.vanta.mjuzik.model.AudioFile;
import pl.vanta.mjuzik.services.ConfigurationService;
import pl.vanta.utils.gui.panels.VListenerPanel;
import pl.vanta.utils.gui.tables.IVTable;
import pl.vanta.utils.gui.tables.VTable;
import pl.vanta.utils.gui.utils.FileTransferHandler;
import pl.vanta.utils.gui.utils.FileTransferListener;

public class PlaylistPanel extends VListenerPanel<PlaylistListener> implements ListSelectionListener
{
	private static final long	serialVersionUID	= 1L;

	private VTable<AudioFile>	table;

	public PlaylistPanel(FileTransferListener fileTransferListener, ConfigurationService configurationService)
	{
		PlaylistTableModel model = new PlaylistTableModel(configurationService);

		FileTransferHandler handler = new FileTransferHandler(MusicUtils.getMusicFilesFilter());
		handler.addFileTransferListener(fileTransferListener);

		this.table = new VTable<AudioFile>(model);
		this.table.setPreferredSize(new Dimension(600, 300));
		this.table.setTransferHandler(handler);
		this.table.addSelectionListener(this);
		this.table.addMouseListener(new MouseAdapter()
		{
			@Override
			public void mouseClicked(MouseEvent e)
			{
				PlaylistPanel.this.mouseClicked(e);
			}
		});

		this.table.addKeyListener(new KeyListener()
		{
			@Override
			public void keyTyped(KeyEvent e)
			{
				PlaylistPanel.this.keyPressed(e);
			}

			@Override
			public void keyReleased(KeyEvent e)
			{
			}

			@Override
			public void keyPressed(KeyEvent e)
			{
			}
		});

		this.setLayout(new BorderLayout());

		this.add(this.table, BorderLayout.CENTER);
	}

	@Override
	public void valueChanged(ListSelectionEvent e)
	{
		for (PlaylistListener listener : this.listeners)
		{
			listener.selectionChanged(e);
		}
	}

	void mouseClicked(MouseEvent e)
	{
		for (PlaylistListener listener : this.listeners)
		{
			if (e.isPopupTrigger())
			{
				listener.popupClick(e);
			}
			else if (e.getClickCount() == 2)
			{
				listener.doubleClick(e);
			}
		}
	}

	void keyPressed(KeyEvent e)
	{
		for (PlaylistListener listener : this.listeners)
		{
			listener.keyPressed(e);
		}
	}

	public IVTable<AudioFile> getTable()
	{
		return this.table;
	}
}